package controllers;

import helpers.GeneralHelper;
import helpers.PaginatorHelper;
import helpers.StringHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.cache.Cache;
import javax.script.Bindings;
import javax.script.CompiledScript;
import javax.script.ScriptContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.images.ImagesService;
import com.google.appengine.api.images.ImagesServiceFactory;

import quercus.CompileScriptEngine;

import systems.Recently;
import systems.RecentlyTag;

import entities.ApplicationConfig;
import entities.Article;
import entities.Category;
import entities.User;

import models.ArticleModel;
import models.CategoryModel;
import models.UserModel;

public class AuthorArticlesServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		ApplicationConfig appConfig = (ApplicationConfig) request.getAttribute("sysConfig");
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String params = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		String id = UrlHelper.getIdFromInfoUrl(params);
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/");
			return ;
		}
		System.out.println(appConfig.getApplicationId());
		UserModel userModel = UserModel.getInstance();
		User author = userModel.getUser(appConfig.getApplicationId(), id);
		
		if (author == null) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		//Get image
		BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
		ImagesService imagesService = ImagesServiceFactory.getImagesService();
		
		String image = "";
		
		if (author != null && author.getAvatar() != null && !author.getAvatar().isEmpty())  {
			 BlobKey blobKey = new BlobKey(author.getAvatar());
			 image = imagesService.getServingUrl(blobKey);
		}
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		//Get article by author and paginator
		int page = 1;
		try {
			page = Integer.parseInt((String) request.getParameter("page"));
		} catch (Exception e) {}
		
		boolean nextPage = false;
		boolean prevPage = false;
		int limit = 20;
		
		ArticleModel articleModel = ArticleModel.getInstance();
		List<Article> articles = Recently.getArticles(appConfig.getApplicationId(), id, "author");
		
		if (page > 1) {
			articles = articleModel.listByAuthor(appConfig.getApplicationId(), id, page, limit, language);
		} else {
			List<Article> lsArticles = articleModel.listByAuthor(appConfig.getApplicationId(), id, page, limit, language);
			if (articles.size() == 0 || articles.size() < lsArticles.size()) {
				for (int i = lsArticles.size() - 1; i >= 0; i--) {
					Recently.insertArticle(appConfig.getApplicationId(), id, "author", lsArticles.get(i));
				}
				articles = Recently.getArticles(appConfig.getApplicationId(), id, "author");
			}
		}
		
		if (articles.size() == limit) {
			nextPage = true;
		}
		
		if (page > 1) {
			prevPage = true;
		}
		
		//Get paginate
		String queryString = request.getQueryString();
		String requestURI = request.getRequestURI();
		PaginatorHelper paginator = new PaginatorHelper(queryString);
		paginator.setUrl(requestURI);
		
		//Get categories
		List<String> cIds = new ArrayList<String>();
		
		for (int i = 0; i < articles.size(); i++) {
			if (!articles.get(i).getCategory().isEmpty()) {
				cIds.add(articles.get(i).getCategory());
			}
		}
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		Map<String, Category> categories = categoryModel.getByListId(appConfig.getApplicationId(), cIds);
		
		request.setAttribute("author", author);
		request.setAttribute("articles", articles);
		request.setAttribute("categories", categories);
		request.setAttribute("paginator", paginator);
		request.setAttribute("prevPage", prevPage);
		request.setAttribute("nextPage", nextPage);
		request.setAttribute("page", page);
		
		try {
			request.getRequestDispatcher("/templates/" + appConfig.getTemplateId() + "/pages/authors.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
		
	}
}
